import React, { useState, useEffect } from 'react';
import { Card } from 'antd';
import { Form, Input, Button, Checkbox, Image, message } from 'antd';

import { Link, history, useSelector, useDispatch } from 'umi';
import styles from '@/assets/css/login.less';
import { loginAPI, verifyUserAPI } from '../apis/user/userAPI';
import { setStorage } from '@/utils/storage';
import { loginInfoAC } from '../models/actions/userAC';
import { addShopApi } from '../apis/gen/genAPI';

import Log from '../components/login/Log';
import ShopIn from './ShopIn';

export default function LogIn(props) {
  const state = useSelector((state) => state.user);
  const [toLogin, setTologin] = useState(false); //false:LOGIN,true:商家入驻
  const dispatch = useDispatch();

  const changeToLog = () => {
    setTologin(!toLogin);
  };
  const onFinish = (values) => {
    console.log('Success:', values);
    asyncLogin(values);
  };

  const asyncLogin = async (userData) => {
    const res = await loginAPI(userData);
    console.log('asyncLogin', res);
    if (res.data.message == '认证成功') {
      setStorage('token', res.data.data.token);
      dispatch(loginInfoAC(res.data.data));
      message.success('登录成功');

      history.push('/home');
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const verify = (par) => ({
    async validator(_, value) {
      const res = await verifyUserAPI(value);
      console.log('verifyUser', res);
      if (res.data) {
        return Promise.reject(new Error('该用户无效'));
      }
    },
  });
  //商家入驻函数
  const onFinish1 = async (values) => {
    // console.log('Success:', values);
    const res = await addShopApi(values);
    if (res.status == 200) {
      message.success('入驻成功');
    }
    // console.log('Success:',res);
  };

  const onFinishFailed1 = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const cardHead = (
    <div className={styles.cardHead}>
      <img src="http://xawn.f3322.net:8002/dist/static/img/logo.png"></img>
      <h3>赤兔养车</h3>
    </div>
  );
  return (
    <div className={styles.loginLayout}>
      <div className="site-card-border-less-wrapper">
        <Card
          title={cardHead}
          bordered={false}
          className={styles.myCard}
          bodyStyle={{ paddingTop: 0 }}
        >
          {toLogin ? (
            <ShopIn
              onFinishFailed1={onFinishFailed1}
              onFinish1={onFinish1}
              changeToLog={changeToLog}
            ></ShopIn>
          ) : (
            <Log
              changeToLog={changeToLog}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              verify={verify}
            ></Log>
          )}

          {props.children}
        </Card>
      </div>
    </div>
  );
}
